package com.nd.qa.shareplate.message;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSONObject;
import com.nd.im.agent.client.service.AgentClient;
import com.nd.im.agent.client.service.ReceiveMessageInterface;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.service.LoginService;
import com.nd.qa.shareplate.service.ProjectService;
import com.nd.qa.shareplate.service.ProjectTaskService;
import com.nd.qa.shareplate.service.ProjectTypeService;
import com.nd.qa.shareplate.service.UserService;
import com.nd.qa.shareplate.util.ApkFileUtil;
import com.nd.qa.shareplate.util.FileUtil;
import com.nd.qa.shareplate.util.FormatTimeUtil;
import com.nd.qa.shareplate.util.HttpUrlUtil;
import com.nd.qa.shareplate.util.HttpUtil;
import com.nd.qa.shareplate.util.JsonUtil;

public class AppReceiveListener implements ServletContextListener{

private static Logger logger = LogManager.getLogger("IMReceiveListener");
	
	private static String userName = "421490";
	private static String projectType = "1";
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.LoginService")
    private LoginService loginService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.UserService")
	private UserService userService;
    
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ProjectService")
	private ProjectService projectService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ProjectTaskService")
	private ProjectTaskService operateProjectService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ProjectTypeService")
	private ProjectTypeService projectTypeService;
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public AppReceiveListener(){
		super();
	}
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		AgentClient imclient;
		try {
				imclient = AgentClient.getInstanceWithAutoLogin("10005782@nd","");//用户名:密码@nd"606290@nd", "606290cq"
				imclient.receiveMessageMgt = new ReceiveMessageInterface() {
					public boolean onSuccess(ArrayList<HashMap<String, Object>> arg1) {
						
		                for(HashMap<String,Object> temp:arg1){
		                    parse(temp);
		                }
		                return false;
		            }
		            @SuppressWarnings("unchecked")
					private void parse(Map<String,Object> message){
		                String sender = (String)message.get("sender");
		                String content = (String)message.get("content");
		                int index=content.indexOf("\r\n\r\n");
		                if(-1==index){
		                    return ;
		                }
		                content=content.substring(index+4);
		                if (content==null||content.contains("mock-entertong_1262976")) {
							return;
						}
		                if (!content.contains("downloadUrl")) {
							return;
						}
		                //TODO 处理99u推送过来的信息
		                logger.info("消息内容："+content);
		                //String headUrl = request.getScheme()+"://"+request.getRemoteAddr()+":"+ request.getLocalPort()+request.getContextPath();
		                HttpUrlUtil httpUrlUtil = new HttpUrlUtil();
		                HashMap<String, Object> ctMap = JsonUtil.toObject(content, HashMap.class);
		                //JSONObject ctMap = JSONObject.parseObject(content);
		                String jobName = String.valueOf(ctMap.get("jobName"));
		                String jobId = String.valueOf(ctMap.get("jobId"));
		                String groupId = String.valueOf(ctMap.get("groupId"));
		                String userObject = httpUrlUtil.connectionUrl(groupId,SysConstant.QUERYBYUSERNAME_URL);
						JSONObject usjson =  (JSONObject) JSONObject.parse(userObject);
			        	JSONObject userJson = (JSONObject) usjson.get("user");
						if (userJson==null) {
							logger.info("不存在该用户信息，groupId为；"+ groupId);
							return;
						}
		                List<JSONObject> codeUrl = (List<JSONObject>)ctMap.get("codeUrl");
		                String buildTime = String.valueOf(ctMap.get("buildTime"));
		                String buildStatus = String.valueOf(ctMap.get("buildStatus"));
		                List downloadUrl = (List)ctMap.get("downloadUrl");
		                if (downloadUrl.size()==0) {
							return;
						}
		                Object downLoadInfo = downloadUrl.get(0);
		                LinkedHashMap<String, Object> jsonObject = (LinkedHashMap<String, Object>) downLoadInfo;
		                String remoteApkUrl = String.valueOf(jsonObject.get("url"));//String.valueOf(downLoadInfo.get("url"));
		                File srcFile = new File(remoteApkUrl);  
		                //String parentPath = srcFile.getParent();    //源文件目录  
		                String fileName = srcFile.getName();        //源文件名称  
		                String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
		                String apkName = prefixName+".apk";
		                String factoryType = (String) ctMap.get("factoryType");
						//查询99u推送的消息
						String msg = httpUrlUtil.connectionUrl(jobId,SysConstant.QUERYMSGINFO_URL);
						logger.info("查询推送信息；"+msg);
						JSONObject msgJson =  (JSONObject) JSONObject.parse(msg);
						String code = msgJson.getString("code");
						if ("-1".equals(code)) {
							//将请求的数据信息录入数据库
							JSONObject param = new JSONObject();
							param.put("jobId", jobId);
							param.put("jobName", jobName);
							param.put("groupId", groupId);
							param.put("buildTime", buildTime);
							param.put("buildStatus", buildStatus);
							param.put("downloadUrl", downloadUrl);
							param.put("codeUrl", codeUrl);
							param.put("factoryType", factoryType);
							httpUrlUtil.connectionUrl(param.toString(),SysConstant.INSERTMESSAGE_URL);
						}else {
							return;
						}
		                //判断ftp文件是否存在，若存在：下载apk至主PC文件下；若不存在，不做操作
						String localLoadPath = SysConstant.localLoadPath;
						String localApkPath = SysConstant.localApkPath;
						String sharePlateApkPath = SysConstant.sharePlateApkPath;
		                try {
		                	File file = new File(localLoadPath);
		                	FileUtil fileUtil = new FileUtil();
		                	if (!file.isDirectory()) {
								FileUtil.buildFile(localLoadPath, true);
							}
							if (HttpUtil.downloadFile(localLoadPath+apkName,remoteApkUrl)) {//HttpUtil.downloadFile("D:\\"+apkName,remoteApkUrl)
								try {
									//判断是否存在该用户信息，若存在，则创建新用户，默认密码1
									File f = new File(sharePlateApkPath);
									if (!file.isDirectory()) {
										FileUtil.buildFile(sharePlateApkPath, true);
									}
									fileUtil.copyFolder(localLoadPath, sharePlateApkPath);//将文件拷贝到服务器上
									String object = httpUrlUtil.connectionUrl(userName,SysConstant.QUERYBYUSERNAME_URL);
									JSONObject json =  (JSONObject) JSONObject.parse(object);
						        	JSONObject uJson = (JSONObject) json.get("user");
									if (uJson==null) {
										//创建新用户
										JSONObject jsonObject2 = new JSONObject();
										jsonObject2.put("userName", userName);
										jsonObject2.put("userPassword", "1");
										httpUrlUtil.connectionUrl(jsonObject2.toString(),SysConstant.REGISTERUSER_URL);
									}
									//获取apk信息
									ApkFileUtil apkFileUtil = new ApkFileUtil();
									String packageName = apkFileUtil.getApkPackageName(localLoadPath+apkName);
									String mainActivity = apkFileUtil.getApkLaunchActivity(localLoadPath+apkName);
									String scriptName = "";
									//获取该项目的最新脚本信息
									JSONObject scriptJson = new JSONObject();
									scriptJson.put("userId", groupId);//groupId
									scriptJson.put("projectType", projectType);
									String scriptRes = httpUrlUtil.connectionUrl(scriptJson.toString(),SysConstant.QUERYLATESTSCRIPTBYUSERID_URL);
									JSONObject typeJson = JSONObject.parseObject(scriptRes);
									System.out.println("scriptRes======================="+scriptRes.length());
									if (typeJson.size()==0||typeJson==null||"".equals(typeJson)||"null".equals(typeJson)) {
										logger.error("没有找到相应版本的脚本信息.........................");
										System.out.println("没有找到相应版本的脚本信息...............................");
										JSONObject logJson = new JSONObject();
										logJson.put("logMsg", "没有找到"+groupId+"用户下，相应版本的脚本信息,请求信息的jobId为 "+jobId);
										logJson.put("beginTime", FormatTimeUtil.dateToStrLong(new Date()));
										//添加日志信息
										httpUrlUtil.connectionUrl(logJson.toString(),SysConstant.ADDLOG_URL);
										return;
									}
									JSONObject script = typeJson.getJSONObject("script");
									String scriptUrl = script.getString("scriptUrl");
									scriptName = script.getString("scriptName");
									/*ProjectType type = new ProjectType();
									type.setShareProjectType(projectType);
									ProjectType pType = projectTypeService.queryInfoByType(type);*/
									//创建信息信息
									//查询项目序列号
									String seqRes = httpUrlUtil.connectionUrl("project_seq",SysConstant.QUERYPROJECTSEQBYNAME_URL);
									JSONObject seqJson = JSONObject.parseObject(seqRes);
									String projectId = seqJson.getString("projectId");
									//项目名称
					                JSONObject jObject = new JSONObject();
					                jObject.put("apkName", apkName);
					                jObject.put("apkPath", localApkPath+apkName);
					                jObject.put("scriptName", scriptName);
					                jObject.put("scriptUrl", scriptUrl);//pType.getShareProjectUrl()
					                jObject.put("projectId", projectId);
					                jObject.put("projectName", "microblog");
					                jObject.put("packageName", packageName);
					                jObject.put("mainActivity", mainActivity);
					                jObject.put("projectType", "1");
					                jObject.put("taskProgress", 0);
					                jObject.put("taskProgressDesc", "准备开始执行脚本");
					                jObject.put("taskStatus", 100);
					                jObject.put("tasdStatusDesc", "脚本准备就绪");
					                jObject.put("userId", groupId);//正式环境修改为groupId   TODO
					                jObject.put("status", "A");
									httpUrlUtil.connectionUrl(jObject.toString(),SysConstant.INSERTPROJECTINFO_URL);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
		            }
				};
	        imclient.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
